package com.jinniulive.platform.module.live;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.TweenAnimationRefreshLayout;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jinniulive.platform.MyApp;
import com.jinniulive.platform.R;
import com.jinniulive.platform.adapter.LiveListAdapter;
import com.jinniulive.platform.bean.LiveListInfo;
import com.jinniulive.platform.bean.LoginInfo;
import com.jinniulive.platform.urls.NetConfig;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;


/**
 * 直播列表页
 */
public class LiveFragment extends Fragment implements View.OnClickListener {
    private LoginInfo info;
    private LiveListAdapter mAdapter;
    private List<LiveListInfo.RoomimgdataBean.RoomDataBean> mData;
    private boolean isPullDown = false;
    private int startIndex = 1;
    private int count = 10;
    private String tokenID;
    private int userID;
    private XRecyclerView recyclerView;
    private boolean canMoreLoad = true;
    private View footer;
    private Typeface typeFace;

    public LiveFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_live, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        MyApp myApp = (MyApp) getActivity().getApplication();
        typeFace = Typeface.createFromAsset(getContext().getAssets(), "fonts/MicrosoftYaHeiGB.ttf");
        //获取当前登录用户的信息主要是获取tokenID和UserID
        info = myApp.getLoginInfo();
        if (info!=null){
            tokenID = info.getUserslist().get(0).getTokenID();
            userID = info.getUserslist().get(0).getUserID();
        }

        initView(view);
        recyclerView.setRefreshHeader(new TweenAnimationRefreshLayout(getContext()));
        recyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallPulse);
        recyclerView.setFootViewText("正在加载", "没有更多了");

        View header = LayoutInflater.from(getContext()).inflate(R.layout.item_live_head, null);
        recyclerView.addItemDecoration(new SpaceItemDecoration(6));

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.addHeaderView(header);

        mAdapter = new LiveListAdapter(getContext());
        download();//获取数据源
        mAdapter.setOnRecyclerViewItemClick(new LiveListAdapter.OnRecyclerViewItemClick() {
            @Override
            public void onRcyclerViewItemClick(int position, View view) {
                // TODO: 2016/12/7 条目点击跳转
            }
        });
        recyclerView.setAdapter(mAdapter);

        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            //下拉刷新
            public void onRefresh() {
                canMoreLoad = true;
                isPullDown = true;
                startIndex = 1;
                count = 10;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        download2();//下载数据
                    }
                }, 1000);
            }

            //加载更多
            @Override
            public void onLoadMore() {
                startIndex += count;
                count = 10;
                isPullDown = false;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        download2();
                    }
                }, 1000);
            }
        });
    }

    private void initView(View view) {
        recyclerView = (XRecyclerView) view.findViewById(R.id.recyclerView_live);
        ImageView ivCollect = (ImageView) view.findViewById(R.id.iv_live_collect);
        ImageView ivSearch = (ImageView) view.findViewById(R.id.iv_live_search);
        ImageView ivMessage = (ImageView) view.findViewById(R.id.iv_live_message);
        ivCollect.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        ivMessage.setOnClickListener(this);
    }

    //下载数据
    private void download() {
        String format = String.format(NetConfig.ZBLIST, tokenID, String.valueOf(userID), String.valueOf(startIndex), String.valueOf(count));
        RequestParams params = new RequestParams(format);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                LiveListInfo liveListInfo = gson.fromJson(result, LiveListInfo.class);
                if (liveListInfo.getErrorcode() == 200) {
                    List<LiveListInfo.RoomimgdataBean.RoomDataBean> roomData = liveListInfo.getRoomimgdata().getRoomData();
                    mData = roomData;
                    mAdapter.setmData(mData);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(getContext(), "取消请求", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    //上拉刷新下拉加载下载数据
    private void download2() {
        String format = String.format(NetConfig.ZBLIST, tokenID, String.valueOf(userID), String.valueOf(startIndex), String.valueOf(count));
        RequestParams params = new RequestParams(format);
        x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        Gson gson = new Gson();
                        LiveListInfo liveListInfo = gson.fromJson(result, LiveListInfo.class);
                        if (liveListInfo.getErrorcode() == 200) {
                            List<LiveListInfo.RoomimgdataBean.RoomDataBean> roomData = liveListInfo.getRoomimgdata().getRoomData();
                            if (isPullDown) {//向下拉
                                mData = roomData;
                                recyclerView.refreshComplete();
                            } else {//向上拉
                                if (roomData.get(0) == null) {
                                    recyclerView.setNoMore(true);
                                } else {
                                    mData.addAll(roomData);
                                    recyclerView.loadMoreComplete();
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        recyclerView.setNoMore(true);
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        Toast.makeText(getContext(), "取消请求", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFinished() {

                    }
                }

        );
    }

    //各点击事件
    @Override
    // TODO: 2016/12/7 实现各点击事件
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_live_collect://收藏

                break;
            case R.id.iv_live_search://搜索
                break;
            case R.id.iv_live_message://消息
                break;
        }
    }
}
